package com.company.manage.common.base;

import com.company.manage.common.persistence.Page;
import com.company.manage.common.utils.DateUtils;
import com.company.manage.common.utils.StringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by HuangYong on 2016/1/21.
 * desc:基础控制器
 */
public class BaseController {
    private static final String TAG = "BaseController";

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            public void setAsText(String text) {
                setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
            }

            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
        /*Date 类型转换*/
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });

//        Timestamp 类型转换
        binder.registerCustomEditor(Timestamp.class,new PropertyEditorSupport(){
            public void setAsText(String text){
                Date date = DateUtils.parseDate(text);
                setValue(date==null?null:new Timestamp(date.getTime()));
            }
        });
    }

    /**
     * 获取page对象
     * @param request
     * @param <T>
     * @return
     */
    public <T> Page<T> getPage(HttpServletRequest request){
        int pageNo = 1;
        int pageSize = 20;
        String orderBy = "id";
        String order = "asc";
        if(StringUtils.isNoneEmpty(request.getParameter("page"))){
            pageNo = Integer.valueOf(request.getParameter("page"));
        }
        if (StringUtils.isNotEmpty(request.getParameter("rows"))){
            pageSize = Integer.valueOf(request.getParameter("rows"));
        }
        if (StringUtils.isNotEmpty(request.getParameter("sort"))){
            orderBy = request.getParameter("sort").toString();
        }
        if (StringUtils.isNotEmpty(request.getParameter("order"))){
            order = request.getParameter("order").toString();
        }

        return new Page<T>(pageNo,pageSize,orderBy,order);
    }

    public <T>Map<String,Object> getEasyUIData(Page<T> page){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("rows",page.getResult());
        map.put("total",page.getTotalCount());
        return map;
    }

} 